/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import sysConfig from "@/config";
import { BigNumber } from 'bignumber.js';

const tool = {}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if(sysConfig.LS_ENCRYPTION == "AES"){
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
        let cacheValue = {
            content: data,
            datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
        }
        return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
        try {
            const value = JSON.parse(localStorage.getItem(key))
            if (value) {
                let nowTime = new Date().getTime()
                if (nowTime > value.datetime && value.datetime != 0) {
                    localStorage.removeItem(key)
                    return null;
                }
				//解密
				if(sysConfig.LS_ENCRYPTION == "AES"){
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
                return value.content
            }
            return null
        } catch (err) {
            return null
        }
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		console.log(_set, '_set')
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config={}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if(cfg.expires){
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if(cfg.path){
			cookieStr += `;path=${cfg.path}`
		}
		if(cfg.domain){
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name){
		var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))
		if(arr != null){
			return unescape(arr[2])
		}else{
			return null
		}
	},
	remove(name){
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if(isFull){
		if(document.exitFullscreen) {
			document.exitFullscreen();
		}else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		}else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	}else{
		if(element.requestFullscreen) {
			element.requestFullscreen();
		}else if(element.msRequestFullscreen) {
			element.msRequestFullscreen();
		}else if(element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		}else if(element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}


/**
 * 匹配状态名称
 * @param {String} type 状态类型
 * @param {Number} val 属性值
 * @returns {String} 返回状态名称名
 */
tool.formatEnmu = function (type, val) {
	let enmu = tool.data.get('ENMU') || {}
	let obj = enmu[type].find(item => {
		return item.value == val
	})
	return obj.label
}
/* 公告状态 */
tool.formatNotice = function (type) {
	let obj = {
		'0' : '默认',
		'1' : '显示',
		'2' : '隐藏',
		'3' : '回收站',
	}
	return obj[type]
}
/* 项目阶段 */
tool.formatStage = function (type, arr) {
	if(arr) { // 返回枚举
		let list = [
			{
				label: '招标',
				value: 1
			},
			{
				label: '预算',
				value: 2
			},
			{
				label: '重计量',
				value: 3
			},
			{
				label: '结算',
				value: 4
			},
		]
		return list
	}
	// 返回值
	let obj = {
		1 : '招标',
		2 : '预算',
		3 : '重计量',
		4 : '结算',
	}
	return obj[type]
}
/* 文件状态 */
tool.formatFileState = function (type, arr) {
	if(arr) { // 返回枚举
		let list = [
			{
				label: '解析中',
				value: 0
			},
			{
				label: '解析失败',
				value: 1
			},
			{
				label: '解析成功',
				value: 2
			},
			{
				label: '作废',
				value: 3
			},
		]
		return list
	}
	// 返回值
	let obj = {
		0 : '解析中',
		1 : '解析失败',
		2 : '解析成功',
		3 : '作废',
	}
	return obj[type]
},
/* 文件状态 */
tool.formatBldTypeArr = function (type, arr) {
	if(arr) { // 返回枚举
		let list = [

			{
				label: '住宅业态',
				value: '1'
			},
			{
				label: '商业业态',
				value: '2'
			},
			{
				label: '地下室',
				value: '5'
			},
		]
		return list
	}
	// 返回值
	let obj = {
		1 : '住宅业态',
		2 : '商业业态',
		5 : '地下室',
	}
	return obj[type]
}

/* 通知类型 */
tool.formatNoticeMode = function (type) {
	let obj = {
		'notice' : '公告',
		'version' : '发版日志',
	}
	return obj[type]
}

/* 多个数求和 */
tool.multiAdd = function (...params) {
 let data = BigNumber(0);
  for (let index = 0; index < params.length; index++) {
    const element = BigNumber(params[index]);
    data = data.plus(element);
  }
  return data.toNumber();
}

/* 输入框不允许输入'e,E'和'+,-' */
tool.clearInput  = function (e) {
let key = e.key;
  if (key === 'e' || key === 'E' || key === '+' || key === '-') {
    e.returnValue = false;
    return false;
  }
  return true;
}

// 金额每三位用一个逗号隔开并保留两位小数
tool.cutMoneyFiter = function(amount) {
	if(amount === 0) {
		return "0.00"
	}
	if(amount == null) {
		return "--"
	}
	//强制保留两位小数
	let f = parseFloat(amount);
	if (isNaN(f)) return amount;
		f = Math.round(amount * 100) / 100;
	let s = f.toString();
	let rs = s.indexOf('.');
	if (rs < 0) {
		rs = s.length;
		s += '.';
	}
	while (s.length < (rs + 1) + 2) {
		s += '0';
	}
	//每三位用一个逗号隔开
	let leftNum=s.split(".")[0];
	let rightNum="."+s.split(".")[1];
	let result;
	//定义数组记录截取后的价格
	let resultArray=new Array();
	if(leftNum.length>3){
		let i=true;
		while (i){
			resultArray.push(leftNum.slice(-3));
			leftNum=leftNum.slice(0,leftNum.length-3);
			if(leftNum.length<4){
				i=false;
			}
		}
		//由于从后向前截取，所以从最后一个开始遍历并存到一个新的数组，顺序调换
		let sortArray=new Array();
		for(let i=resultArray.length-1;i>=0;i--){
			sortArray.push(resultArray[i]);
		}
		result=leftNum+","+sortArray.join(",")+rightNum;

	}else {
		result=s;
	}
	// 负数 截取负号后面的 ，
	if(amount < 0) {
		let code = result.slice(1,2)
		if(code == ',') {
			let end = result.slice(2)
			result = '-' + end
		}
	}
	return result;
}

/* 计算金额比例 */
tool.getAmountRate = function (nodeAllocationCount, nodeCount) {
		if(!nodeAllocationCount) {
			return '0%'
		}
		return (nodeAllocationCount / nodeCount * 100).toFixed(2) + '%';
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm') {
	if(!date){
		return '暂无数据'
	}
	date = new Date(date)
	var o = {
		"M+" : date.getMonth()+1,                 //月份
		"d+" : date.getDate(),                    //日
		"h+" : date.getHours(),                   //小时
		"m+" : date.getMinutes(),                 //分
		"s+" : date.getSeconds(),                 //秒
		"q+" : Math.floor((date.getMonth()+3)/3), //季度
		"S"  : date.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if(!num.includes('.')){
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
},

// 添加日期范围
tool.addDateRange = function(params, dateRange, propName) {
  let search = params
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {}
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0]
    search.params['endTime'] = dateRange[1]
  } else {
    search.params['begin' + propName] = dateRange[0]
    search.params['end' + propName] = dateRange[1]
  }
  return search
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
tool.handleTree = function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  var childrenListMap = {}
  var tree = []
  for (let d of data) {
    let id = d[config.id]
    childrenListMap[id] = d
    if (!d[config.childrenList]) {
      d[config.childrenList] = []
    }
  }

  for (let d of data) {
    let parentId = d[config.parentId]
    let parentObj = childrenListMap[parentId]
    if (!parentObj) {
      tree.push(d)
    } else {
      parentObj[config.childrenList].push(d)
    }
  }
  return tree
},



/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data){
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data){
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher){
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config={}){
			if(secretKey.length % 8 != 0){
				console.warn("[SCUI error]: 秘钥长度需为8的倍数，否则解密将会失败。")
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config={}){
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}

export default tool

// 防抖

export function debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    }
}
